<?php
/*
 * 足球阵型采集
 */

namespace app\sports\lineup\service;

use think\Db;
use think\Exception;
use app\common\HTTP;
use app\common\OSS;
use think\facade\Log;
use app\sports\lineup\model\LineupModel;
use app\common\InstanceTrait;
use app\sports\lineup\service\LineupDetailCaiji;

class LineupCaiji
{
    private $user = '';
    private  $secret ='';
//    接口名:足球比赛阵容采集
//    接口频次:10/s
    private $url = 'open.sportnanoapi.com/api/sports/football/match/lineup';

    protected function __construct()
    {
        $this->user = Env::get('nami.user');
        $this->secret = Env::get('nami.secret');
    }

    /*
     * 采集足球阵型数据
     * $id 纳米比赛的id
     */
    public function Execs($id=2214059)
    {
        try {
            $lineupressult = json_decode(HTTP::getInstance()->doGet($this->url."?user=$this->user&secret=$this->secret&id=$id"), true);
            $modeldata = LineupModel::getInstance()->QueryId($id);
            if (!$modeldata){
//                添加
                    $data = [
                    'nami_match_id'  => $id,
                    'left_team'      => $lineupressult['home_formation'],
                    'away_formation' =>$lineupressult['away_formation'],
                    'create_time'    =>date('Y-m-d H:i:s',time()),
                    'update_time'    =>date('Y-m-d H:i:s',time()),
                ];
                $result=LineupModel::getInstance()->InsertLineup($data);
                if (!$result) throw new Exception('足球球队阵容入库失败');
            }else{
//                更新
                $data=[
                    'left_team'      => $lineupressult['home_formation'],
                    'away_formation' =>$lineupressult['away_formation'],
                    'update_time'    =>date('Y-m-d H:i:s',time()),
                ];
                $result=LineupModel::getInstance()->UpdateLineup($id,$data);
                if (!$result) throw new Exception('足球球队阵容更新失败');
            }
//            引入足球阵型详细信息处理service
            $home=LineupDetailCaiji::getInstance()->LineupDetail($lineupressult['home'],$id,1);
            $away=LineupDetailCaiji::getInstance()->LineupDetail($lineupressult['away'],$id,2);

            if (!$home) throw new Exception('足球阵容主队信息插入失败');
            if (!$away) throw new Exception('足球阵容客队信息插入失败');
            Log::log('info','足球阵容采集入库成功');
        }catch(Exception $e){
            Log::error('足球阵容错误:'.$e->getMessage());
            return [];
        }


    }
}